package com.wing.sell.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.sell.model.entity.AgentDueSubjectCategory;
import com.wing.sell.model.entity.CustomerDueSubjectCategory;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.sell.model.entity.CustomerComplaintLabelCategory;
import com.wing.sell.model.request.CustomerComplaintLabelCategoryForm;
import com.wing.sell.service.CustomerComplaintLabelCategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-客诉标签分类管理", tags = "#/sell/customerComplaintLabelCategory")
@RestController("customerComplaintLabelCategoryController")
@RequestMapping("sell/admin/customerComplaintLabelCategory")
@RequiredArgsConstructor
public class CustomerComplaintLabelCategoryController {

    private final CustomerComplaintLabelCategoryService customerComplaintLabelCategoryService;


    @ApiOperation(value = "查询所有客诉标签分类", notes = "搜索")
    @GetMapping("/list")
    public PageResult<CustomerComplaintLabelCategory> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "create_time") String sort,
            @RequestParam(defaultValue = "asc") String order,String name){
        Page<CustomerComplaintLabelCategory> pg = new Page<>(page, limit);
        QueryWrapper<CustomerComplaintLabelCategory> queryWrapper = new QueryWrapper<>();
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }
        //搜索
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        IPage<CustomerComplaintLabelCategory> list = customerComplaintLabelCategoryService.getBaseMapper().selectPage(pg, queryWrapper);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加客诉标签分类", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(CustomerComplaintLabelCategoryForm.Add.class) CustomerComplaintLabelCategoryForm customerComplaintLabelCategoryForm) {
        //为终极分类时不允许添加子类
        if(customerComplaintLabelCategoryForm.getParentId()!=null){
            CustomerComplaintLabelCategory parent = customerComplaintLabelCategoryService.getById(customerComplaintLabelCategoryForm.getParentId());
            if(parent != null && parent.getIsFinal() != null && parent.getIsFinal()){
                return JsonResult.fail("添加失败，该上级分类为终极分类");
            }
        }
        if (customerComplaintLabelCategoryService.add(customerComplaintLabelCategoryForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改客诉标签分类", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(CustomerComplaintLabelCategoryForm.Update.class) CustomerComplaintLabelCategoryForm customerComplaintLabelCategoryForm) {
        CustomerComplaintLabelCategory customerComplaintLabelCategory = customerComplaintLabelCategoryService.getById(customerComplaintLabelCategoryForm.getId());
        if(customerComplaintLabelCategory == null){
            return JsonResult.fail("修改失败！");
        }
        if(customerComplaintLabelCategoryForm.getParentId()!=null){
            CustomerComplaintLabelCategory parent = customerComplaintLabelCategoryService.getById(customerComplaintLabelCategoryForm.getParentId());
            if(parent != null && parent.getIsFinal() != null && parent.getIsFinal()){
                return JsonResult.fail("修改失败，该上级分类为终极分类");
            }
            int count = customerComplaintLabelCategoryService.count(new QueryWrapper<CustomerComplaintLabelCategory>().eq("parent_id", customerComplaintLabelCategory.getId()));
            if(count > 0 && customerComplaintLabelCategoryForm.getIsFinal() != null && customerComplaintLabelCategoryForm.getIsFinal()){
                return JsonResult.fail("该分类有下级分类，不可置为终极分类");
            }
        }
        if(customerComplaintLabelCategoryForm!=null&&customerComplaintLabelCategoryForm.getIsFinal()==null){
            customerComplaintLabelCategoryForm.setIsFinal(false);
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(CustomerComplaintLabelCategory.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(customerComplaintLabelCategoryForm, customerComplaintLabelCategory, copyOptions);
        if (customerComplaintLabelCategoryService.updateById(customerComplaintLabelCategory)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除客诉标签分类", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "customerComplaintLabelCategoryId", value = "客诉标签分类id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long customerComplaintLabelCategoryId) {
        try {
            if (customerComplaintLabelCategoryService.delete(customerComplaintLabelCategoryId)) {
                return JsonResult.success("删除成功");
            }
            return JsonResult.fail("删除失败");
        } catch (BusinessException e) {
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return JsonResult.fail(e.getMessage());
        }
    }

    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @GetMapping("/getTreeData")
    public JsonResult getTreeData(Long selectId) {
        return customerComplaintLabelCategoryService.getTreeData(selectId);
    }

    @ApiOperation(value = "启用", notes = "启用")
    @PostMapping("/enable")
    public JsonResult enable(Long id) {
        if (customerComplaintLabelCategoryService.enable(id) > 0) {
            return JsonResult.success("启用成功");
        }
        return JsonResult.fail("启用失败");
    }

    @ApiOperation(value = "停用", notes = "停用")
    @PostMapping("/disable")
    public JsonResult disable(Long id) {
        if (customerComplaintLabelCategoryService.disable(id) > 0) {
            return JsonResult.success("停用成功");
        }
        return JsonResult.fail("停用失败");
    }

}
